package com.wdc.回溯;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

@SuppressWarnings("all")
public class E05Leetcode40 {
    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    int[] used ;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        used = new int[candidates.length];
        Arrays.sort(candidates);
        backtracking(candidates,target,0,0);
        return result;
    }
    void backtracking(int[] candidates , int target , int stratIndex , int sum){
        //结束条件
        if (sum > target){
            return;
        }
        if (sum == target){
//            if (!result.contains(path))
            result.add(new ArrayList<>(path));
            return;
        }
        //循环遍历
        for (int i = stratIndex; i < candidates.length; i++) {
            if (sum > target){
                break;
            }
            //去重
            if (i >0 && candidates[i] == candidates[i -1] && used[i - 1] == 0){
                continue;
            }
            used[i] = 1;
            sum += candidates[i];
            path.add(candidates[i]);
            //递归求深度
            backtracking(candidates,target,i + 1,sum);
            //回溯
            used[i] = 0;
            sum -= candidates[i];
            path.removeLast();

        }

    }

    public static void main(String[] args) {
        int[] candidates = {10,1,2,7,6,1,5};
        E05Leetcode40 e05Leetcode40 = new E05Leetcode40();
        System.out.println(e05Leetcode40.combinationSum2(candidates, 8));
    }
}
